package com.mcxx.modules.miniSalvation.family.service.write;

import cn.hutool.core.date.DateField;
import com.mcxx.common.exception.BizException;
import com.mcxx.modules.miniSalvation.family.entity.FamilyMemberEntity;
import com.mcxx.modules.miniSalvation.family.param.ExpireFamilyParam;
import com.mcxx.modules.miniSalvation.family.service.read.FamilyMemberReadService;
import com.mcxx.modules.miniSalvation.fundpay.service.read.FundPayReadService;
import com.mcxx.modules.miniSalvation.order.dao.write.SuspendMemberWriteDao;
import com.mcxx.modules.miniSalvation.order.entity.*;
import com.mcxx.modules.miniSalvation.order.service.read.OrderCareLinkReadService;
import com.mcxx.modules.miniSalvation.order.service.write.OrderCareLinkWriteService;
import com.mcxx.modules.miniSalvation.order.service.write.OrderWriteService;
import com.mcxx.modules.miniSalvation.order.service.write.SuspendApproveWriteService;
import com.mcxx.modules.miniSalvation.salary.entity.MemberSalaryEntity;
import com.mcxx.modules.miniSalvation.salary.service.read.FamilyMemberSalaryReadService;
import com.mcxx.modules.miniSalvation.salary.service.write.FamilyMemberSalaryWriteService;
import com.mcxx.modules.miniSalvation.salary.service.write.SalaryChangeWriteService;
import com.mcxx.result.BaseResult;
import com.mcxx.util.Constant;
import com.mcxx.util.DateUtil;
import com.mcxx.util.FailureCode;
import com.yinhai.ta404.core.security.vo.UserAccountVo;
import com.yinhai.ta404.core.service.BaseService;
import com.yinhai.ta404.core.transaction.annotation.TaTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service("suspendMemberWriteService")
@TaTransactional
public class SuspendMemberWriteService extends BaseService {
    @Autowired
    private SuspendMemberWriteDao suspendMemberWriteDao;
    @Autowired
    private SuspendFamilyWriteService suspendFamilyWriteService;
    @Autowired
    private FamilyMemberSalaryReadService familyMemberSalaryReadService;
    @Autowired
    private SuspendMemberWriteService suspendMemberWriteService;
    @Autowired
    private OrderWriteService orderWriteService;
    @Autowired
    private FamilyMemberSalaryWriteService familyMemberSalaryWriteService;
    @Autowired
    private SalaryChangeWriteService salaryChangeWriteService;
    @Autowired
    private FundPayReadService fundPayReadService;
    @Autowired
    private SuspendApproveWriteService suspendApproveWriteService;
    @Autowired
    private FamilyMemberReadService familyMemberReadService;
    @Autowired
    private OrderCareLinkReadService orderCareLinkReadService;
    @Autowired
    private OrderCareLinkWriteService orderCareLinkWriteService;


    public int saveSuspendMember(SuspendMemberEntity memberEntity){
        return suspendMemberWriteDao.insertIgnoreNull(memberEntity);
    }


    public int deleteById(String id) {
        return  suspendMemberWriteDao.deleteById(id);
    }



    public BaseResult<Boolean> suspendFamily(ExpireFamilyParam param, List<OrderEntity> list, UserAccountVo userAccountVo) {
        BaseResult<Boolean> result = new BaseResult<>();
        if (CollectionUtils.isEmpty(list)) {
            throw new BizException(FailureCode.ERR_10003);
        }

        List<String> familyIds = new ArrayList<>();
        int i = 0;
        for (OrderEntity orderEntity : list) {

            familyIds.add(orderEntity.getFamilyId());

            String suspendFamilyId = Constant.getUUID();

            List<MemberSalaryEntity> memberSaList = familyMemberSalaryReadService.queryMemberSumSalaryByOrderId(orderEntity.getOrderId());

            orderEntity.setDataFrom("1");
            if(StringUtils.isNotBlank(param.getPrimaryKeys())){
                String[] pIds = param.getPrimaryKeys().split(",");
                SuspendFamilyEntity entity = new SuspendFamilyEntity();
                entity.setId(pIds[i]);
                entity.setState(Constant.SuspendState.SUSPEND);

                if(Constant.UserLevel.COUNTY.equals(userAccountVo.getAreaLevel())){

                    orderEntity.setDataFrom("2");


                    SuspendApproveEntity approveEntity = new SuspendApproveEntity();
                    approveEntity.setId(Constant.getUUID());
                    approveEntity.setCheckOpinion(param.getCheckOption());
                    approveEntity.setCheckResult(param.getCheckResult());
                    approveEntity.setCheckPeople(userAccountVo.getUsername());
                    approveEntity.setCheckType(Constant.SuspendApproveType.SUSPEND_S);
                    approveEntity.setOperator(userAccountVo.getUserId());
                    approveEntity.setOperatorDate(new Date());
                    approveEntity.setOrgId(userAccountVo.getOrgId());
                    approveEntity.setSuspendId(pIds[i]);
                    suspendApproveWriteService.insertIgnoreNull(approveEntity);
                    if("0".equals(param.getCheckOption())){
                        entity.setState(Constant.SuspendState.N_SUSPEND);
                        orderEntity.setDataFrom("3");
                    }else if("1".equals(param.getCheckOption())){

                        fundPayReadService.verifyFundPayThrow(orderEntity.getBusinessType(), orderEntity.getCountyCode(),
                                orderEntity.getStandType(), param.getStopMonth(), orderEntity.getSupplyType(), Constant.FundType.CAPITAL_FUND_PAY);

                        familyMemberSalaryWriteService.modifySalary(memberSaList, orderEntity.getOrderId(),param.getStopMonth());
                        salaryChangeWriteService.insertSalaryChange(orderEntity, param.getStopMonth(), "批量暂停",Constant.SalaryChangeType.CHANGE_SUSPEND);

                        List<FamilyMemberEntity> familyMemberEntities = familyMemberReadService.listByFamilyId(orderEntity.getFamilyId());

                        for(FamilyMemberEntity familyMemberEntity:familyMemberEntities) {

                            OrderCareLinkEntity orderCareLinkEntity = orderCareLinkReadService.getCareIdByIdCard(familyMemberEntity.getIdcard());
                            if (orderCareLinkEntity != null) {

                                this.updateByCareId(orderCareLinkEntity.getCareId(),orderCareLinkEntity.getId(), familyMemberEntity.getId(), DateUtil.getMonthString());
                            }
                        }

                    }
                    entity.setStartMonth(param.getStopMonth());
                    suspendFamilyWriteService.updateIgnoreNull(entity);
                }
            }else{

                suspendFamilyWriteService.saveSuspendFamily(param, userAccountVo, orderEntity,suspendFamilyId);
                for (MemberSalaryEntity memberSalaryEntity : memberSaList) {
                    SuspendMemberEntity suMember = new SuspendMemberEntity();
                    suMember.setSusFamilyId(suspendFamilyId);
                    suMember.setBusinessType(memberSalaryEntity.getBusinessType());
                    suMember.setId(Constant.getUUID());
                    suMember.setMemberId(memberSalaryEntity.getMemberId());
                    suMember.setFamilyId(memberSalaryEntity.getFamilyId());
                    suMember.setOrderId(orderEntity.getOrderId());
                    suMember.setMemSalaryId(memberSalaryEntity.getId());
                    suspendMemberWriteService.saveSuspendMember(suMember);
                }
            }

            orderWriteService.modifyOrder(orderEntity,"", param.getStopMonth(), userAccountVo,Constant.SuspendState.SUSPEND);
            i++;
        }

        return result;
    }

    private void updateByCareId(String careId,String id,String memberId,String lastMonth){
        lastMonth = cn.hutool.core.date.DateUtil.parse(lastMonth, "yyyyMM").offset(DateField.MONTH,-1).toString("yyyy-MM-dd");

        OrderCareLinkEntity careLinkEntity = new OrderCareLinkEntity();
        careLinkEntity.setState("02");
        careLinkEntity.setId(id);
        careLinkEntity.setCareId(careId);
        careLinkEntity.setMemberId(memberId);
        careLinkEntity.setEndMonth(lastMonth);
        careLinkEntity.setUpdateTime(new Date());
        orderCareLinkWriteService.updateByCareId(careLinkEntity);
    }

}
